/**
 * @file Functions.cpp
 * @author Benjamin Mayes <bdm8233@rit.edu>
 */

// This code is taken straight from http://stackoverflow.com/questions/448944/c-non-blocking-keyboard-input#448982
// This guy needs to be properly thanked and credited.

#include "functions.h"

#if defined(__APPLE__) || defined(__linux__)
struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;
    
    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));
    
    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv);
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}
#endif

unsigned char single_char_input() {
    char c = 0;
    #ifdef _WIN32 
        while( !kbhit() ) {
            //TODO: Determine sleep to use
            //usleep( 100000 ); 
        }
        c = getch();
    #elif defined(__APPLE__) || defined(__linux__)
        set_conio_terminal_mode();
        while( !kbhit() ) {
            usleep( 100000 );
        }
        c = (char)getch();
        reset_terminal_mode();
    #else
        std::cin >> c;
    #endif
    return c;
}
